function setupFH5JsBridge(callback) {
    var ua = navigator.userAgent.toLowerCase();
    var isIOS  = ua.match(/(iphone|ipod|ipad);?/i);
    var isAndroid = ua.match('android');
    if(isIOS){
        if('FH5JsBridge' in window) {
            return callback(FH5JsBridge)
        }
        if('FH5Callbacks' in window) {
            return window.FH5Callbacks.push(callback)
        }
        window.FH5Callbacks = [callback];
        var FH5Iframe = document.createElement('iframe');
        FH5Iframe.style.display = 'none';
        FH5Iframe.src = 'fh5jsbridge://__BRIDGE_LOADED__';
        document.documentElement.appendChild(FH5Iframe);
        setTimeout(() => {
            document.documentElement.removeChild(FH5Iframe)
        }, 0);
    } 
    if(isAndroid) {
        if('FH5JsBridge' in window) {
            window.FH5JsBridge.initBridge(callback);
        } else {
            document.addEventListener('FH5JsBridgeReady',function(){
                window.FH5JsBridge.initBridge(callback)
            },false)
        }
    }
}

setupFH5JsBridge(function(bridge){
    //业务方注册的接口，有业务js实现，供native调用

    //通知native跳转信息，用户back按钮处理，
    window.addEventListener('popstate',function(event){
        onPopstateChange({
            url:location.href || '',
            title:document.title || '',
            state: event.state || {}
        })
    })
})


function jsBridge() {
    return new Promise((resolve,reject)=>{
        const res = ()=> {
            if(window.FH5JsBridge) {
                resolve(window.FH5JsBridge);
            } else {
                setTimeout(res,50);
            }
        }
        res();
    })
}


async function callHandler(funcName,options,callback) {
    const bridge = await jsBridge();
    return new Promise((resovle,reject)=>{
        if(callback) {
            bridge.callHandler(funcName,options,callback);
        } else {
            bridge.callHandler(funcName,options,res=>{
                if(res && res.status === 0) {
                    resovle(res)
                } else {
                    reject(new Error(`errorCode ${res.status}: ${res.errMsg}`));
                }
            });
        }

    })
}

window.callFH5Handler = callHandler;

export function post(options,callback) {
    callHandler('post',options,callback)
}

export function get(options,callback) {
    callHandler('get',options,callback)
}

export function getSSOTicket(options,callback) {
    callHandler('getSSOTicket',options,callback)
}

export function setData(options,callback) {
    callHandler('setData',options,callback)
}

export function getData(options,callback) {
    callHandler('getData',options,callback)
}

export function removeData(options,callback) {
    callHandler('removeData',options,callback)
}

export function onPopstateChange(options,callback) {
    callHandler('onPopstateChange',options,callback)
}



